package weaver.interfaces.jz.action;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Joiner;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/3/25
 * @Description 人员入职同步食堂
 * @Author AdminZm
 */
public class HrmEntrySyncLeopenAction implements Action {

    BaseBean baseBean = new BaseBean();

    @Override
    public String execute(RequestInfo requestInfo) {
        RequestManager requestManager = requestInfo.getRequestManager();
        int billId = requestManager.getBillid();
        String tableName = requestManager.getBillTableName();
        String requestId = requestInfo.getRequestid();
        User user = requestManager.getUser();
        baseBean.writeLog("HrmEntrySyncLeopenAction start:" + requestId + "、" + billId + "、" + tableName);
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            String sfzhm = null;
            rs.executeQuery("SELECT * FROM " + tableName + " WHERE id = ?", billId);
            if (rs.next()) {
                sfzhm = rs.getString("sfzhm");
            }
            baseBean.writeLog("HrmEntrySyncLeopenAction sfzhm:" + sfzhm);
            if (StringUtils.isEmpty(sfzhm)) {
                return Action.SUCCESS;
            }

            String locationIds = rs.getPropValue("jzjg_canteen_zm_prop", "push_canteen_locationids");
            if (StringUtils.isEmpty(locationIds)) {
                baseBean.writeLog("HrmEntrySyncLeopenAction locationIds is null.");
                return Action.SUCCESS;
            }

            String ryId = null;
            String gh = null;
            String mobile = null;
            String locationid = null;
            rs.executeQuery("SELECT id, mobile, workcode, locationid FROM hrmresource WHERE certificatenum = ?", sfzhm);
            if (rs.next()) {
                ryId = rs.getString("id");
                gh = rs.getString("workcode");
                mobile = rs.getString("mobile");
                locationid = rs.getString("locationid");
            }
            if (StringUtils.isEmpty(locationid)) {
                baseBean.writeLog("HrmEntrySyncLeopenAction locationid is null.");
                return Action.SUCCESS;
            }
            List<String> locationIdList = Arrays.asList(locationIds.split(","));
            if (CollectionUtils.isEmpty(locationIdList) || !locationIdList.contains(locationid)) {
                baseBean.writeLog("HrmEntrySyncLeopenAction not need push.");
                return Action.SUCCESS;
            }

            // 获取食堂组织信息
            Map<String, String> leopenOrgIdMap = getLeopenOrgId();
            if (CollectionUtils.isEmpty(leopenOrgIdMap)) {
                baseBean.writeLog("HrmEntrySyncLeopenAction leopenOrgIdMap is null.");
                return Action.SUCCESS;
            }

            String url = null;
            List<Map<String, String>> contentMapAllList = new ArrayList<>();
            Map<String, String> contentMap = new HashMap<>();
            rs.execute("SELECT dt.*, main.jkurl FROM uf_lncymbpzglb_dt1 dt, uf_lncymbpzglb main WHERE dt.mainid = main.id " +
                    " AND dt.zt = 0 AND main.zt = 0 AND main.jklx = 0 ");
            while (rs.next()) {
                url = rs.getString("jkurl");
                String jkcszd = rs.getString("jkcszd");
                if (StringUtils.isEmpty(url) || StringUtils.isEmpty(jkcszd)) {
                    continue;
                }
                String sfqyzdysql = rs.getString("sfqyzdysql");
                String qzlybm = rs.getString("qzlybm");
                String qzlyzdm = rs.getString("qzlyzdm");
                String lybzjlx = rs.getString("lybzjlx");
                String lybzjzdm = rs.getString("lybzjzdm");
                String qzsql = rs.getString("qzsql");
                if ((!StringUtils.equals(sfqyzdysql, "0")) && (StringUtils.isEmpty(qzlybm) || StringUtils.isEmpty(qzlyzdm)
                        || StringUtils.isEmpty(lybzjlx) || StringUtils.isEmpty(lybzjzdm))) {
                    continue;
                }
                if (StringUtils.equals(sfqyzdysql, "0") && StringUtils.isEmpty(qzsql)) {
                    continue;
                }
                String valueTemp = null;
                if (StringUtils.equals(sfqyzdysql, "0")) {
                    rs1.executeQuery(qzsql, ryId);
                    if (rs1.next()) {
                        valueTemp = rs1.getString(1);
                    }
                    if (StringUtils.equals(jkcszd, "orgNum") && StringUtils.isNotEmpty(valueTemp)) {
                        contentMap.put(jkcszd, leopenOrgIdMap.get(valueTemp));
                    } else {
                        contentMap.put(jkcszd, valueTemp);
                    }
                }

                if (!StringUtils.equals(sfqyzdysql, "0")) {
                    String sql = "SELECT " + qzlyzdm + " FROM " + qzlybm + " WHERE " + lybzjzdm + " = ?";
                    if (StringUtils.equals(lybzjlx, "0")) {
                        rs1.executeQuery(sql, ryId);
                    } else if (StringUtils.equals(lybzjlx, "1")) {
                        rs1.executeQuery(sql, gh);
                    } else if (StringUtils.equals(lybzjlx, "2")) {
                        rs1.executeQuery(sql, mobile);
                    } else if (StringUtils.equals(lybzjlx, "3")) {
                        rs1.executeQuery(sql, sfzhm);
                    }
                    if (rs1.next()) {
                        valueTemp = rs1.getString(qzlyzdm);
                        if (StringUtils.equals(jkcszd, "orgNum") && StringUtils.isNotEmpty(valueTemp)) {
                            contentMap.put(jkcszd, leopenOrgIdMap.get(valueTemp));
                        } else {
                            contentMap.put(jkcszd, valueTemp);
                        }
                    }
                }
            }
            String url_fk = null;
            List<Map<String, String>> contentMapAllList_fk = new ArrayList<>();
            Map<String, String> contentMap_fk = new HashMap<>();
            rs.execute("SELECT dt.*, main.jkurl FROM uf_lncymbpzglb_dt1 dt, uf_lncymbpzglb main WHERE dt.mainid = main.id " +
                    " AND dt.zt = 0 AND main.zt = 0 AND main.jklx = 1 ");
            while (rs.next()) {
                url_fk = rs.getString("jkurl");
                String jkcszd = rs.getString("jkcszd");
                if (StringUtils.isEmpty(url_fk) || StringUtils.isEmpty(jkcszd)) {
                    continue;
                }
                String sfqyzdysql = rs.getString("sfqyzdysql");
                String qzlybm = rs.getString("qzlybm");
                String qzlyzdm = rs.getString("qzlyzdm");
                String lybzjlx = rs.getString("lybzjlx");
                String lybzjzdm = rs.getString("lybzjzdm");
                String qzsql = rs.getString("qzsql");
                if ((!StringUtils.equals(sfqyzdysql, "0")) && (StringUtils.isEmpty(qzlybm) || StringUtils.isEmpty(qzlyzdm)
                        || StringUtils.isEmpty(lybzjlx) || StringUtils.isEmpty(lybzjzdm))) {
                    continue;
                }
                if (StringUtils.equals(sfqyzdysql, "0") && StringUtils.isEmpty(qzsql)) {
                    continue;
                }
                String valueTemp = null;
                if (StringUtils.equals(sfqyzdysql, "0")) {
                    rs1.executeQuery(qzsql, ryId);
                    if (rs1.next()) {
                        valueTemp = rs1.getString(1);
                    }
                    contentMap_fk.put(jkcszd, valueTemp);
                }

                if (!StringUtils.equals(sfqyzdysql, "0")) {
                    String sql = "SELECT " + qzlyzdm + " FROM " + qzlybm + " WHERE " + lybzjzdm + " = ?";
                    if (StringUtils.equals(lybzjlx, "0")) {
                        rs1.executeQuery(sql, ryId);
                    } else if (StringUtils.equals(lybzjlx, "1")) {
                        rs1.executeQuery(sql, gh);
                    } else if (StringUtils.equals(lybzjlx, "2")) {
                        rs1.executeQuery(sql, mobile);
                    } else if (StringUtils.equals(lybzjlx, "3")) {
                        rs1.executeQuery(sql, sfzhm);
                    }
                    if (rs1.next()) {
                        valueTemp = rs1.getString(qzlyzdm);
                        contentMap_fk.put(jkcszd, valueTemp);
                    }
                }
            }
            baseBean.writeLog("HrmEntrySyncLeopenAction contentMap、contentMap_fk:" + contentMap + "、" + contentMap_fk);
            if (CollectionUtils.isEmpty(contentMap)) {
                return Action.SUCCESS;
            }
            String modeId = rs.getPropValue("jzjg_canteen_zm_prop", "lncytsjlb_mode_id");
            String cusId = rs.getPropValue("jzjg_canteen_zm_prop", "lncytsjlb_cus_id");
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");

            contentMapAllList.add(contentMap);
            String uuid = UUID.randomUUID() + "0";
            rs.executeUpdate("INSERT INTO uf_lncytsjlb (lx, ly, lcqqidtzzjid, qqcs, jkurl, formmodeid,MODEUUID,modedatacreater," +
                    "modedatacreatertype, modedatacreatedate, modedatacreatetime) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                    "0", "0", requestId, JSONObject.toJSONString(contentMapAllList), url, modeId, uuid, "1",
                    "0", sdfDate.format(new Date()), sdfTime.format(new Date()));
            String dataId = null;
            rs.executeQuery("SELECT id FROM uf_lncytsjlb WHERE MODEUUID = ?", uuid);
            if (rs.next()) {
                dataId = rs.getString("id");
            }
            contentMapAllList_fk.add(contentMap_fk);
            uuid = UUID.randomUUID() + "1";
            rs.executeUpdate("INSERT INTO uf_lncytsjlb (lx, ly, lcqqidtzzjid, qqcs, jkurl, formmodeid,MODEUUID,modedatacreater," +
                            "modedatacreatertype, modedatacreatedate, modedatacreatetime) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                    "1", "0", requestId, JSONObject.toJSONString(contentMapAllList_fk), url_fk, modeId, uuid, "1",
                    "0", sdfDate.format(new Date()), sdfTime.format(new Date()));
            String dataId_fk = null;
            rs.executeQuery("SELECT id FROM uf_lncytsjlb WHERE MODEUUID = ?", uuid);
            if (rs.next()) {
                dataId_fk = rs.getString("id");
            }
            // 新增用户
            pushLeopen(contentMapAllList, url, dataId);
            // 发卡
            pushLeopen(contentMapAllList_fk, url_fk, dataId_fk);

        } catch (Exception e) {
            baseBean.writeLog("HrmEntrySyncLeopenAction error:" + e);
        }
        baseBean.writeLog("HrmEntrySyncLeopenAction end.");
        return Action.SUCCESS;
    }

    public Map<String, String> getLeopenOrgId() {
        baseBean.writeLog("getLeopenOrgId start.");
        Map<String, String> leopenOrgIdMap = new HashMap<>();
        try {
            Map<String, List> paramMap = new HashMap<>();
            paramMap.put("orgNumList", new ArrayList());
            paramMap.put("orgIdList", new ArrayList());
            RecordSet createRs = new RecordSet();
            String appid = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appid");
            String appsecret = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appsecret");
            //请求内容字典排序，转换为String
            String content = JSON.toJSONString(paramMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);

            //构造请求验签参数
            Map<String, Object> map = new TreeMap<>();
            map.put("appid", appid);
            map.put("version", "1.0.0");
            map.put("signtype", "md5");
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));
            map.put("nonce", RandomUtil.randomNumbers(10));
            map.put("content", content);
            //生成sign，防篡改
            String toSignStr = Joiner.on("&")
                    .useForNull("")
                    .withKeyValueSeparator("=")
                    .join(map) + "&appsecret=" + appsecret;


            // md5/sha256 加签（其他方式待提供）
            String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();
            map.put("sign", sign);

            //post请求
            map.replace("content", paramMap);

            String host = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_host");
            HttpRequest requestT = HttpUtil.createPost(host + "/leopen/customer/org/query");
            requestT.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
            HttpResponse responseT = requestT.execute();

            //返回值验签
            Map<String, Object> resultMap = JSON.parseObject(
                    responseT.body(),
                    new TypeReference<SortedMap<String, Object>>() {
                    }.getType()
            );
            if (CollectionUtils.isEmpty(resultMap)) {
                baseBean.writeLog("getLeopenOrgId resultMap is null.");
                return leopenOrgIdMap;
            }
            Object code = resultMap.get("code");
            if (code == null || code == "" || new BigDecimal(code.toString()).compareTo(new BigDecimal("10000")) != 0) {
                baseBean.writeLog("getLeopenOrgId get failed:" + code);
                return leopenOrgIdMap;
            }
            Object data = resultMap.get("data");
            if (data == null || data == "") {
                baseBean.writeLog("getLeopenOrgId data is null.");
                return leopenOrgIdMap;
            }
            List<Map<String, Object>> dataMapList = (List<Map<String, Object>>) data;
            for (Map<String, Object> dataMap : dataMapList) {
                Object orgName = dataMap.get("orgName");
                Object orgId = dataMap.get("orgId");
                Object ifDel = dataMap.get("ifDel");
                if (orgName == null || orgName == "" || orgId == null || orgId == "" || ifDel == null || ifDel == "" || new BigDecimal(ifDel.toString()).compareTo(new BigDecimal("2")) != 0) {
                    continue;
                }
                leopenOrgIdMap.put(orgName.toString(), orgId.toString());
            }
        } catch (Exception e) {
            baseBean.writeLog("getLeopenOrgId error:" + e);
        }
        baseBean.writeLog("getLeopenOrgId end.");
        return leopenOrgIdMap;
    }

    public void pushLeopen(List<Map<String, String>> bodyMapList, String url, String dataId) {
        baseBean.writeLog("HrmEntrySyncLeopenAction pushLeopen start:" + url + "、" + dataId);
        RecordSet createRs = new RecordSet();
        try {
            String appid = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appid");
            String appsecret = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appsecret");
            //请求内容字典排序，转换为String
            String content = JSON.toJSONString(bodyMapList, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);

            //构造请求验签参数
            Map<String, Object> map = new TreeMap<>();
            map.put("appid", appid);
            map.put("version", "1.0.0");
            map.put("signtype", "md5");
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));
            map.put("nonce", RandomUtil.randomNumbers(10));
            map.put("content", content);
            //生成sign，防篡改
            String toSignStr = Joiner.on("&")
                    .useForNull("")
                    .withKeyValueSeparator("=")
                    .join(map) + "&appsecret=" + appsecret;


            // md5/sha256 加签（其他方式待提供）
            String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();

            map.put("sign", sign);

            //post请求
            map.replace("content", bodyMapList);
            String host = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_host");
            HttpRequest request = HttpUtil.createPost(host + url);
            request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
            HttpResponse response = request.execute();

            //返回值验签
            Map<String, Object> resultMap = JSON.parseObject(
                    response.body(),
                    new TypeReference<SortedMap<String, Object>>() {
                    }.getType()
            );
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET xyjg = ? WHERE id = ?", JSONObject.toJSONString(resultMap), dataId);
            Object code = resultMap.get("code");
            if (code != null && (StringUtils.equals(code.toString(), "200") || StringUtils.equals(code.toString(), "10000"))) {
                createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 0 WHERE id = ?", dataId);
            } else {
                createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 1 WHERE id = ?", dataId);
            }
        } catch (Exception e) {
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET ycyy = ? WHERE id = ?", e, dataId);
        }
        baseBean.writeLog("HrmEntrySyncLeopenAction pushLeopen end.");
    }

    public void createHrm(List<Map<String, String>> bodyMapList, String url, String dataId) {
        baseBean.writeLog("HrmEntrySyncLeopenAction createHrm start:" + url + "、" + dataId);
        RecordSet createRs = new RecordSet();
        String appid = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appid");
        String appsecret = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appsecret");
        //请求内容字典排序，转换为String
        String content = JSON.toJSONString(bodyMapList, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);

        //构造请求验签参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appid", appid);
        map.put("version", "1.0.0");
        map.put("signtype", "md5");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("nonce", RandomUtil.randomNumbers(10));
        map.put("content", content);
        //生成sign，防篡改
        String toSignStr = Joiner.on("&")
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(map) + "&appsecret=" + appsecret;


        // md5/sha256 加签（其他方式待提供）
        String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();

        map.put("sign", sign);

        //post请求
        map.replace("content", bodyMapList);
        String host = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_host");
        HttpRequest request = HttpUtil.createPost(host + url);
        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
        HttpResponse response = request.execute();

        //返回值验签
        Map<String, Object> resultMap = JSON.parseObject(
                response.body(),
                new TypeReference<SortedMap<String, Object>>() {
                }.getType()
        );
        createRs.executeUpdate("UPDATE uf_lncytsjlb SET xyjg = ? WHERE id = ?", JSONObject.toJSONString(resultMap), dataId);
        Object code = resultMap.get("code");
        if (code != null && (StringUtils.equals(code.toString(), "200") || StringUtils.equals(code.toString(), "10000"))) {
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 0 WHERE id = ?", dataId);
        } else {
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 1 WHERE id = ?", dataId);
        }
        baseBean.writeLog("HrmEntrySyncLeopenAction createHrm end.");
//        return JSON.toJSONString(resultMap.get("data"),
//                SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
    }

    public void createCard(List<Map<String, String>> bodyMapList, String url, String dataId) {
        baseBean.writeLog("HrmEntrySyncLeopenAction createCard start:" + url + "、" + dataId);
        RecordSet createRs = new RecordSet();
        String appid = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appid");
        String appsecret = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_appsecret");
        //请求内容字典排序，转换为String
        String content = JSON.toJSONString(bodyMapList, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);

        //构造请求验签参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appid", appid);
        map.put("version", "1.0.0");
        map.put("signtype", "md5");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("nonce", RandomUtil.randomNumbers(10));
        map.put("content", content);
        //生成sign，防篡改
        String toSignStr = Joiner.on("&")
                .useForNull("")
                .withKeyValueSeparator("=")
                .join(map) + "&appsecret=" + appsecret;


        // md5/sha256 加签（其他方式待提供）
        String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();

        map.put("sign", sign);

        //post请求
        map.replace("content", bodyMapList);
        String host = createRs.getPropValue("jzjg_canteen_zm_prop", "canteen_host");
        HttpRequest request = HttpUtil.createPost(host + url);
        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
        HttpResponse response = request.execute();

        //返回值验签
        Map<String, Object> resultMap = JSON.parseObject(
                response.body(),
                new TypeReference<SortedMap<String, Object>>() {
                }.getType()
        );
        createRs.executeUpdate("UPDATE uf_lncytsjlb SET xyjg = ? WHERE id = ?", JSONObject.toJSONString(resultMap), dataId);
        Object code = resultMap.get("code");
        if (code != null && (StringUtils.equals(code.toString(), "200") || StringUtils.equals(code.toString(), "10000"))) {
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 0 WHERE id = ?", dataId);
        } else {
            createRs.executeUpdate("UPDATE uf_lncytsjlb SET zt = 1 WHERE id = ?", dataId);
        }
        baseBean.writeLog("HrmEntrySyncLeopenAction createCard end.");
    }
}
